package com.android.happymall.utils;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.happymall.MainActivity;
import com.android.happymall.R;
import com.android.happymall.activity.GoodsDetailActivity;
import com.android.happymall.model.member.AddressData;
import com.android.happymall.view.detail.ProvinceBean;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.elbbbird.android.socialsdk.SocialSDK;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 项目中用到的工具类
 */
public class ObjectUtils {
    public static final boolean LOG = true;
    private static Toast toast;

    //判断网络是否可以连接
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    //白色状态栏
    public static void StatusBarWhiteBg(Activity context, boolean iswhite) {
        if (iswhite) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (SystemBarHelper.isMIUI6Later() || SystemBarHelper.isFlyme4Later() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    SystemBarHelper.setStatusBarDarkMode(context, 1);
                    SystemBarHelper.tintStatusBar(context, Color.parseColor("#ffffff"), 0);
                } else {
                    SystemBarHelper.tintStatusBar(context, Color.parseColor("#66bbbbbb"), 0);
                }
            }
        } else {

            SystemBarHelper.setStatusBarDarkMode(context, 2);
            SystemBarHelper.tintStatusBar(context, context.getResources().getColor(R.color.app_title));

        }

    }


    public static SpannableStringBuilder getPartColor(int color, String content, int start, int end) {
        ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        builder.setSpan(redSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        return builder;
    }

    /**
     * 数据连接情况  无缓存直接显示无网状态
     */
    public static void GetDataNet(LinearLayout clickResetnetwork, RelativeLayout progress, int type) {
        switch (type) {
            case 1:
                clickResetnetwork.setVisibility(View.GONE);
                progress.setVisibility(View.GONE);
                break;
            case 2:
                clickResetnetwork.setVisibility(View.VISIBLE);
                progress.setVisibility(View.GONE);
                break;
            case 3:
                clickResetnetwork.setVisibility(View.GONE);
                progress.setVisibility(View.VISIBLE);
                break;
            case 4:
                clickResetnetwork.setVisibility(View.VISIBLE);
                progress.setVisibility(View.GONE);
                break;

        }

    }

    public static void toast(Context context,
                             String content) {
        if (toast == null) {
            toast = Toast.makeText(context, content,
                    Toast.LENGTH_SHORT);
        } else {
            toast.setText(content);
        }
        toast.show();
    }

    public static void ToDetailActivity(Context mcontext, int iskai, String id, String common_id) {
        Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, iskai);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID, id);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID, common_id);
        mcontext.startActivity(intent);
    }


    // 将时间戳转为字符串表现形式1
    public static String getStrTime(String cc_time, String show) {
        String re_StrTime;
        SimpleDateFormat sdf = new SimpleDateFormat(show);
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }


    //Glide加载图片
    public static void photo(Context mcontext, String load, ImageView imgview) {
        Glide.with(mcontext.getApplicationContext())
                .load(load)
                .crossFade()
                .error(R.mipmap.img_err).placeholder(R.mipmap.img_ing)
                .into(imgview);

    }

    //Glide加载图片
    public static void photo2(Context mcontext, String load, ImageView imgview) {
        Glide.with(mcontext.getApplicationContext())
                .load(load)
                .crossFade()
                .error(R.mipmap.img_err)
                .into(imgview);

    }

    //Glide加载图片
    public static void photoCircle(Context mcontext, String load, ImageView imgview) {
        RequestManager glideRequest = Glide.with(mcontext.getApplicationContext());
        glideRequest.load(load)
                .transform(new GlideCircleTransform(mcontext))
                .error(R.mipmap.img_err).placeholder(R.mipmap.avater)
                .into(imgview);

    }

    /**
     * 从控件所在位置移动到控件的底部/从控件的底部移动到控件所在位置
     *
     * @return
     */
    public static TranslateAnimation moveToViewBottom(int type) {

        if (type == 0) {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
            mHiddenAction.setDuration(500);
            return mHiddenAction;
        } else {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            mHiddenAction.setDuration(500);
            return mHiddenAction;
        }
    }

    private static ArrayList<ProvinceBean> options1Items = new ArrayList<>();
    private static ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private static ArrayList<ArrayList<ArrayList<ProvinceBean>>> options3Items = new ArrayList<>();

    /**
     * 地区选择三级联动
     *
     * @param context
     */
    public static void redAddress(final Context context) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                // 读取本地json文件
                InputStream district_inputStream = context.getResources().openRawResource(
                        R.raw.city);
                String addressString = getMyString(district_inputStream);
                Type listType = new TypeToken<ArrayList<AddressData>>() {
                }.getType();
                ArrayList<AddressData> address = GsonUtils.parseJSONArray(addressString, listType);
                for (int i = 0; i < address.size(); i++) {
                    //选项1
                    options1Items.add(new ProvinceBean(i + "", address.get(i).getName()));
                    List<AddressData.SubBean> city = address.get(i).getSub();
                    //选项2
                    ArrayList<String> options2Item = new ArrayList<>();
//                    ArrayList<ArrayList<IPickerViewData>> options3Items_01 = new ArrayList<>();
                    ArrayList<ArrayList<ProvinceBean>> options3Items_01 = new ArrayList<>();
                    for (int j = 0; j < city.size(); j++) {
                        options2Item.add(city.get(j).getName());
                        List<AddressData.SubBean.SubBean2> area = city.get(j).getSub();
//                        ArrayList<IPickerViewData> options3Items_01_01 = new ArrayList<>();
                        ArrayList<ProvinceBean> options3Items_01_01 = new ArrayList<>();

                        if (area.size() == 0) {
//                            options3Items_01_01.add(new PickerViewData(city.get(j).getName()));
                            options3Items_01_01.add(new ProvinceBean(city.get(j).getId(), city.get(j).getName()));
                        } else {
                            for (int k = 0; k < area.size(); k++) {
//                                options3Items_01_01.add(new PickerViewData(area.get(k).getName()));
                                options3Items_01_01.add(new ProvinceBean(area.get(k).getId(), area.get(k).getName()));
                            }
                        }
                        options3Items_01.add(options3Items_01_01);
                    }
//                    options3Items.add(options3Items_01);
                    options3Items.add(options3Items_01);
                    options2Items.add(options2Item);
                }
            }
        });
    }

    /**
     * 得到省
     *
     * @return
     */
    public static ArrayList<ProvinceBean> getAddress1() {
        return options1Items;
    }

    /**
     * 得到市
     *
     * @return
     */
    public static ArrayList<ArrayList<String>> getAddress2() {
        return options2Items;
    }

    /**
     * 得到区
     *
     * @return
     */
    public static ArrayList<ArrayList<ArrayList<ProvinceBean>>> getAddress3() {
        return options3Items;
    }


    /**
     * 读取文件
     *
     * @param inputStream
     * @return
     */
    public static String getMyString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }


    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    //获取缓存大小
    public static class CacheDataManager {

        public static String getTotalCacheSize(Context context) throws Exception {

            long cacheSize = getFolderSize(context.getCacheDir());

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                cacheSize += getFolderSize(context.getExternalCacheDir());

            }

            return getFormatSize(cacheSize);

        }

        public static void clearAllCache(Context context) {

            deleteDir(context.getCacheDir());

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                deleteDir(context.getExternalCacheDir());

            }

        }

        private static boolean deleteDir(File dir) {

            if (dir != null && dir.isDirectory()) {

                String[] children = dir.list();

                for (int i = 0; i < children.length; i++) {

                    boolean success = deleteDir(new File(dir, children[i]));

                    if (!success) {

                        return false;

                    }

                }

            }

            return dir.delete();

        }

// 获取文件

// Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/

// 目录，一般放一些长时间保存的数据

// Context.getExternalCacheDir() -->

// SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据

        public static long getFolderSize(File file) throws Exception {

            long size = 0;

            try {

                File[] fileList = file.listFiles();

                for (int i = 0; i < fileList.length; i++) {

// 如果下面还有文件

                    if (fileList[i].isDirectory()) {

                        size = size + getFolderSize(fileList[i]);

                    } else {

                        size = size + fileList[i].length();

                    }

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

            return size;

        }

        /**

         * 格式化单位

         *

         * @param size

         */

        public static String getFormatSize(double size) {
              if(size==0)
              {
                  return  "0";
              }
            double kiloByte = size / 1024;

            if (kiloByte < 1) {

                return size + "Byte";

            }

            double megaByte = kiloByte / 1024;

            if (megaByte < 1) {

                BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));

                return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";

            }

            double gigaByte = megaByte / 1024;

            if (gigaByte < 1) {

                BigDecimal result2 = new BigDecimal(Double.toString(megaByte));

                return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";

            }

            double teraBytes = gigaByte / 1024;

            if (teraBytes < 1) {

                BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));

                return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";

            }

            BigDecimal result4 = new BigDecimal(teraBytes);

            return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";

        }

    }

    public static HashMap<String, String> getHeader(Context context) {
        String getid = LoginState.getInstance().getid(context);
        String token = LoginState.getInstance().getUserInfo(context, 2);
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("TOKEN", token);
        return header;
    }

    public static void reLogin(Context context) {
        LoginState.getInstance().clearInfo(context);
        String  login_type = LoginState.getInstance().getUserInfo(context, 3);
        if (login_type.equals("1")) {
            SocialSDK.revokeWeibo(context);

        } else if (login_type.equals("2")) {

            SocialSDK.revokeWeChat(context);
        } else if (login_type.equals("3")) {

            SocialSDK.revokeQQ(context);
        }
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("TabSelect",3);
        context.startActivity(intent);
        toast(context, "登录过期，请先登录");
    }
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
}
